<?php

namespace CommonBundle\Controller\Api;

use CommonBundle\Controller\RestController;
use CommonBundle\Service\BalanceService;
use CommonBundle\Service\UserService;
use CommonBundle\View\ApiView;
use CommonBundle\View\SingleDetailApiViewMixin;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Swagger\Annotations as SWG;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @Route("/api/balances", name="api-balance-")
 */
class BalanceController extends RestController
{
    use ApiView, SingleDetailApiViewMixin;

    public function __construct() {
        $this->serviceClass = BalanceService::class;
    }

    public function commonFilter() {
        return ['user' => $this->getUser()];
    }

    /**
     * @Route("/exchange/{sourceCurrency}-{targetCurrency}/{amount}", name="exchange", methods={"PUT"},
     *     requirements={"sourceCurrency":"amount", "targetCurrency":"withdrawablePoint", "amount":"\d+(\.\d+)?"}
     * )
     * @SWG\Response(
     *     response=200,
     *     description="Exchange amount to withdrawable point.",
     * )
     * @param UserInterface $user
     * @param $sourceCurrency
     * @param $targetCurrency
     * @param $amount
     * @return Response
     */
    public function exchangeAction(UserInterface $user, $sourceCurrency, $targetCurrency, $amount): Response
    {
        /** @var BalanceService $service */
        $service = $this->get($this->serviceClass);

        $res = $service->exchange($user, $user, $sourceCurrency, $targetCurrency, $amount,
            'Exchange to withdrawable point.',
            'Exchange from amount.');

        return $res ? $this->Success(): $this->Warning('Exchange fail.');
    }

    /**
     * @Route("/transfer/{userId}/{currency}/{amount}", name="transfer", methods={"PUT"},
     *     requirements={"userId":"\d+", "currency":"(amount)", "amount":"\d+(\.\d+)?"}
     * )
     * @SWG\Response(
     *     response=200,
     *     description="Transfer balances",
     * )
     * @param $userId
     * @param $currency
     * @param $amount
     * @return Response
     */
    public function transferAction($userId, $currency, $amount): Response
    {
        /** @var BalanceService $service */
        $service = $this->get($this->serviceClass);
        $userService = $this->get(UserService::class);

        $fromUser = $this->getUser();
        $toUser = $userService->get($userId);

        $res = $service->exchange($fromUser, $toUser, $currency, $currency, $amount,
            'Transfer balance to user.',
            'Transfer balance from user.');

        return $res ? $this->Success(): $this->Warning('Exchange fail.');
    }
}
